import intervalToRepeat from '../helpers/intervalToRepeat';
import queueRepeatTaskNameBuilder from '../helpers/queueRepeatTaskNameBuilder';
import { stopQueueTask } from './stopTask';
import { JOB_TASK_TYPE_MAP, AVILIABLE_TASK_MAP } from '../../common/constants';

export default async function stopRepeatTask({
	refId,
	taskType,
	taskIdx,
	interval,
}) {
	const {
		app: {
			queues,
			model: { Task, Asset, Job },
		},
	} = this;

	let ref;
	if (JOB_TASK_TYPE_MAP[taskType]) {
		ref = await Job.findById(refId);
		if (!ref) {
			throw new Error(`cannot found Job by Id: [${taskType}]${refId}`);
		}
		if (AVILIABLE_TASK_MAP[taskType]) {
			ref[`${taskType}IsStarted`] = ref[`${taskType}IsStarted`].map(x => false);
		} else {
			ref[`${taskType}IsStarted`] = false;
		}
		await ref.save();
	} else {
		ref = await Asset.findById(refId);
		if (ref) {
			ref.isStarted = false;
			await ref.save();
		} else {
			this.log.debug({ assetId: refId }, '资产查询失败');
		}
	}

	if (!queues[taskType]) return;

	await queues[taskType].removeRepeatable(
		queueRepeatTaskNameBuilder({
			refId,
			taskType,
			taskIdx,
			triggerType: 'schedule',
		}),
		intervalToRepeat(interval)
	);

	const query = { refId, taskType, status: { $in: ['waiting', 'acitve'] } };
	if (taskIdx) {
		query.taskIdx = taskIdx;
	}
	const tasks = await Task.find(query);
	await Promise.all(
		tasks.map(async task => {
			const queueTask = await queues[task.taskType]?.getJobFromId(task.taskId);
			if (queueTask) {
				await stopQueueTask(queueTask);
			}

			task.status = 'stopped';
			task.endTime = new Date();
			await task.save();
		})
	);
}
